package com.goldcn.file.service;

import com.goldcn.Application;
import com.goldcn.common.util.CommonUtils;
import com.goldcn.common.util.UuidUtils;
import com.goldcn.file.vo.FileVo;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSInputFile;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * Created by kylin.woo on 3/4/2016.
 */
@Service("uploadService")
@Transactional
public class UploadService {

    @Autowired
    MongoTemplate template;

    public FileVo uploadFiles(MultipartFile file){
        try {
            if (!file.isEmpty()) {
                String fileName = file.getOriginalFilename();
                String suffix = fileName.substring(fileName.lastIndexOf("."));
                String newFile = UuidUtils.uuid();
                GridFS gfsPhoto = new GridFS(template.getDb());
                GridFSInputFile gfsFile = gfsPhoto.createFile(file.getInputStream());
                gfsFile.setFilename(newFile+suffix);
                gfsFile.save();

                System.out.println(newFile+suffix);

                FileVo vo = new FileVo();
                vo.setFileName(newFile+suffix);
                vo.setFileSize(file.getSize());
                vo.setFileSuffix(suffix);
                vo.setFileUploadName(fileName);
                return vo;

            }else
                return null;

        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public void downLoad(HttpServletResponse response,String fileName){
        try{
            GridFS fs = new GridFS(template.getDb());
            GridFSDBFile dbFile = fs.findOne(fileName);
            response.setContentLengthLong(dbFile.getLength());

            DateFormat df = new SimpleDateFormat(
                    "EEE, dd MMM yyyy HH:mm:ss z", Locale.ENGLISH);
            Date uploadDate = dbFile.getUploadDate();
            String lastModified = df.format(uploadDate);
            response.setContentType("image/*");
            long maxAge = 60L * 60L;
            response.setHeader("Cache-Control", "max-age=" + maxAge);
            response.setHeader("Last-Modified", lastModified);
            response.setDateHeader("Expires", uploadDate.getTime() + maxAge
                    * 1000L);

            dbFile.writeTo(response.getOutputStream());
        }catch(Exception e){
            e.printStackTrace();
        }

    }



}
